package net.lxch.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class HashUtil {
    public static final String ALGORITHM_SHA1 = "SHA-1";
    public static final String ALGORITHM_SHA = "SHA";
    public static final String ALGORITHM_MD5 = "MD5";
    public static final String ALGORITHM_SHA256 = "SHA-256";
    private static final String CANDIDATE_STRING = "abcdefghijklmnopqrstuvwxyz0123456789";
    private static final int RANDOM_STRING_LENGTH = 32;

    public static String createRandomString() {
        StringBuilder randomString = new StringBuilder();
        SecureRandom random = new SecureRandom();

        for(int i = 0; i < RANDOM_STRING_LENGTH; ++i) {
            int startIndex = Math.abs(random.nextInt()) % CANDIDATE_STRING.length();
            randomString.append(CANDIDATE_STRING, startIndex, startIndex + 1);
        }

        return randomString.toString();
    }


    public static String hash(String value, String algorithm) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            digest.update(value.getBytes());
            byte[] messageDigest = digest.digest();
            StringBuilder hexString = new StringBuilder();

            for (byte aMessageDigest : messageDigest) {
                String shaHex = Integer.toHexString(aMessageDigest & 255);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException var10) {
            var10.printStackTrace();
            return "";
        }
    }
}
